package getsmart.project.activity;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import getsmart.project.R;
import getsmart.project.database.Bab_Pelajaran;
import getsmart.project.database.JSONParser;
import getsmart.project.database.LogActivity;
import getsmart.project.mailsender.GMailSender;
import getsmart.project.mailsender.LogCreator;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class UpdateServerToBelajar extends Activity {
	private String url = "http://192.168.1.17:1991/GetSmart/listPelajaran.php";
	Button updateBtn;
	Bab_Pelajaran updateBab;
	JSONObject  jObject;
	//public JSONObject jObject = null;
	List<Integer> valuesIDBAB = new ArrayList<Integer>();
	List<Integer> valuesID_Pelajaran = new ArrayList<Integer>();
	List<Integer> valuesID_Kelas = new ArrayList<Integer>();
	List<Integer> valuesUrutan = new ArrayList<Integer>();
	List<String> valuesInggris = new ArrayList<String>();
	List<String> valuesConten = new ArrayList<String>();
	List<String> valuesIndoensia = new ArrayList<String>();
	public Integer[] dataIDBAB;
	public Integer[] dataID_Pelajaran;
	public Integer[] dataID_Kelas;
	public Integer[] dataUrutan;
	public String[] dataInggris;
	public String[] dataConten;
	public String[] dataIndonesia;
	private String xResult = "";
	
	public static final int MESSAGE_DOWNLOAD_STARTED = 1000;
	public static final int MESSAGE_DOWNLOAD_COMPLETE = 1001;
	public static final int MESSAGE_UPDATE_PROGRESS_BAR = 1002;
	public static final int MESSAGE_DOWNLOAD_CANCELED = 1003;
	public static final int MESSAGE_CONNECTING_STARTED = 1004;
	public static final int MESSAGE_ENCOUNTERED_ERROR = 1005;

	private UpdateServerToBelajar thisActivity;
	private Thread downloaderThread;
	private ProgressDialog progressDialog;
	private Runnable sendMail;
	public String sentMessage = ""; // isi pesan yang akan dikirim 

	public void onCreate(Bundle as) {
		super.onCreate(as);
		setContentView(R.layout.update_data_from_server);
		thisActivity = this;
		updateBab = new Bab_Pelajaran(this);
		updateBtn = (Button) findViewById(R.id.btnUpdatePelajaranFromServer);
		final LogActivity logAct = new LogActivity(thisActivity);
        LogCreator logCre = new LogCreator();
        final String[] filenameList;
        filenameList = logCre.createLog(this,logAct);
		try {
			parse();
		} catch (Exception e) {
			e.printStackTrace();
		}
		Toast.makeText(this, "Berhasil " + jObject, Toast.LENGTH_LONG).show();
		dataIDBAB = new Integer[valuesIDBAB.size()];
		dataID_Pelajaran = new Integer[valuesID_Pelajaran.size()];
		dataID_Kelas = new Integer[valuesID_Kelas.size()];
		dataUrutan = new Integer[valuesUrutan.size()];
		dataInggris = new String[valuesInggris.size()];
		dataConten = new String[valuesConten.size()];
		dataIndonesia = new String[valuesIndoensia.size()];
		for (int posisi = 0; posisi < valuesIDBAB.size(); posisi++) {
			dataIDBAB[posisi] = valuesIDBAB.get(posisi);
			dataID_Pelajaran[posisi] = valuesID_Pelajaran.get(posisi);
			dataID_Kelas[posisi] = valuesID_Kelas.get(posisi);
			dataUrutan[posisi] = valuesUrutan.get(posisi);
			dataInggris[posisi] = valuesInggris.get(posisi);
			dataConten[posisi] = valuesConten.get(posisi);
			dataIndonesia[posisi] = valuesIndoensia.get(posisi);
		}
		updateBtn.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				for (int i = 0; i < dataIDBAB.length; i++) {
//					updateBab.addDataPelajaran(dataIDBAB[i], dataID_Pelajaran[i], dataID_Kelas[i], dataInggris[i], dataConten[i], dataIndonesia[i]);
					
				}
			//Kirim email stat ke target
				sentMessage = "Akan diisi laporan";
				sendMail = new Runnable() {
					@Override
					public void run() {
						// TODO Auto-generated method stub
						
				    	Log.d("Button", "Clicked");
					    try {   
					        GMailSender sender = new GMailSender("getsmartsatunol@gmail.com", "satunolkpproject");
					//                    MimeMultipart _multipart = new MimeMultipart();
					        for (int i=0; i<filenameList.length; i++){
					        	sender.addAttachment(filenameList[i]);
					        }
					        sender.sendMail("Log Activity",   
					                "Berikut log activity aplikasi",   
					                "getsmartsatunol@gmail.com",   
					                "kemit_lastsword@yahoo.com");   
					        Log.d("Mail", "Send");
					    } catch (Exception e) {   
					        Log.e("SendMail", e.getMessage(), e);   
					    }
					    logAct.close();
					}
				};
				Thread thread = new Thread(sendMail);
				thread.start();
				thread.stop();
			}
		});
		//Toast.makeText(this, "Nilai dari " + jObject, Toast.LENGTH_LONG).show();
		
	}

	private void parse() throws Exception {
		JSONParser jp = new JSONParser();
		try{
			jObject = jp.AmbilJson(url);
			JSONArray menuitemArray = jObject.getJSONArray("Pelajaran");
			Integer ID_BAB = 0;
			Integer ID_Pelajaran = 0;
			Integer ID_Kelas = 0;
			Integer Urutan = 0;
			String Inggris = "";
			String Conten = "";
			String Indoensia = "";
			for (int i = 0; i < menuitemArray.length(); i++) {
				ID_BAB = Integer.parseInt(menuitemArray.getJSONObject(i)
						.getString("ID_BAB").toString());
				ID_Pelajaran = Integer.parseInt(menuitemArray.getJSONObject(i)
						.getString("ID_Pelajaran").toString());
				ID_Kelas = Integer.parseInt(menuitemArray.getJSONObject(i)
						.getString("ID_Kelas").toString());
				Urutan = Integer.parseInt(menuitemArray.getJSONObject(i)
						.getString("Urutan").toString());
				Inggris = menuitemArray.getJSONObject(i).getString("Inggris")
						.toString();
				Conten = menuitemArray.getJSONObject(i).getString("Content")
						.toString();
				Indoensia = menuitemArray.getJSONObject(i).getString("Indonesia")
						.toString();

				valuesIDBAB.add(ID_BAB);
				valuesID_Pelajaran.add(ID_Pelajaran);
				valuesID_Kelas.add(ID_Kelas);
				valuesUrutan.add(Urutan);
				valuesInggris.add(Inggris);
				valuesConten.add(Conten);
				valuesIndoensia.add(Indoensia);
			}
		}
		catch(Exception e){
			Toast.makeText(thisActivity, "Maslahanya " + e.getMessage(), Toast.LENGTH_SHORT).show();
		}
		
		

	}

	/**
	 * Method untuk Mengirimkan data keserver event by button login diklik
	 * 
	 * @param view
	 */
	public String getRequest(String Url) {

		String sret = "";
		HttpClient client = new DefaultHttpClient();
		HttpGet request = new HttpGet(Url);
		try {
			HttpResponse response = client.execute(request);
			sret = request(response);

		} catch (Exception ex) {
			Toast.makeText(this, "Gagal " + jObject, Toast.LENGTH_SHORT).show();
		}
		return sret;

	}

	/**
	 * Method untuk Menenrima data dari server
	 * 
	 * @param response
	 * @return
	 */
	public static String request(HttpResponse response) {
		String result = "";
		try {
			InputStream in = response.getEntity().getContent();
			BufferedReader reader = new BufferedReader(
					new InputStreamReader(in));
			StringBuilder str = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				str.append(line + "\n");
			}
			in.close();
			result = str.toString();
		} catch (Exception ex) {
			result = "Error";
		}
		return result;
	}
	
	
	public void dismissCurrentProgressDialog() {
		if (progressDialog != null) {
			progressDialog.hide();
			progressDialog.dismiss();
			progressDialog = null;
		}
	}

	/**
	 * Displays a message to the user, in the form of a Toast.
	 * 
	 * @param message
	 *            Message to be displayed.
	 */
	public void displayMessage(String message) {
		if (message != null) {
			Toast.makeText(thisActivity, message, Toast.LENGTH_SHORT).show();
		}
	}
}
